﻿/// <reference path="../../../../_3rd part/SharePoint.d.ts"/>
/// <reference path="../../../../_3rd part/MicrosoftAjax.d.ts"/>
/// <reference path="../../../../_3rd part/SP.GanttControl.d.ts"/>
/// <reference path="../../../../_3rd part/SP.JsGrid.d.ts"/>
var spdevlab;
(function (spdevlab) {
    (function (fields) {
        var VisaFieldHelper = (function () {
            function VisaFieldHelper() {
            }
            VisaFieldHelper.UpdateValues = function (textBoxes, value) {
                for (var i = 0; i < textBoxes.length; i++) {
                    textBoxes[i].value = VisaFieldHelper.ParseValuePart(value, i);
                }
            };

            VisaFieldHelper.ParseValuePart = function (value, partIndex) {
                if (value && (value.length == 16)) {
                    return value.substring(partIndex * 4, (partIndex + 1) * 4);
                }

                return "";
            };
            return VisaFieldHelper;
        })();
        fields.VisaFieldHelper = VisaFieldHelper;

        var VisaField = (function () {
            function VisaField(fieldName) {
                this._fieldIds = [];
                this._errorContainerId = null;
                this._fieldName = fieldName;
            }
            VisaField.prototype._wrapIntoInput = function (renderCtx, val, index) {
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                var inputContainerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + '_VisaField_' + index;

                this._fieldIds[index] = inputContainerId;

                return "<input type='text' id='" + inputContainerId + "' value='" + val + "' maxlength='4' size='4' />";
            };

            VisaField.prototype._wrapErrorArea = function (renderCtx) {
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                var errorContainerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + '_VisaField_Error';

                this._errorContainerId = errorContainerId;

                return "<span id='" + errorContainerId + "' class='ms-formvalidation ms-csrformvalidation'></span>";
            };

            VisaField.prototype._onGetValue = function () {
                var result = '';

                if (this._fieldIds.length == 4) {
                    for (var key in this._fieldIds) {
                        result += (document.getElementById(this._fieldIds[key])).value;
                    }
                }

                return result;
            };

            VisaField.prototype._getViewStringValue = function (value) {
                if (value && value.length == 16) {
                    var arr = [];

                    for (var i = 0; i < 4; i++)
                        arr.push(VisaFieldHelper.ParseValuePart(value, i));

                    return arr.join("-");
                }

                return "";
            };

            VisaField.prototype.viewTemplate = function (renderCtx, field, listItem, listSchema) {
                var fieldValue = "";

                if (renderCtx != null && renderCtx.CurrentItem != null)
                    fieldValue = eval('renderCtx.CurrentItem.' + field.Name);

                if (fieldValue.length == 16)
                    fieldValue = this._getViewStringValue(fieldValue);

                return fieldValue;
            };

            VisaField.prototype._initValidators = function (renderCtx) {
                var _this = this;
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);

                var visaFieldValidators = new SPClientForms.ClientValidation.ValidatorSet();

                if (formCtx.fieldSchema.Required) {
                    visaFieldValidators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator());
                }

                visaFieldValidators.RegisterValidator(new spdevlab.fields.VisaFieldValidator());

                formCtx.registerValidationErrorCallback(formCtx.fieldName, function (error) {
                    _this.onError(error);
                });
                formCtx.registerClientValidator(formCtx.fieldName, visaFieldValidators);
            };

            VisaField.prototype.newFormTemplate = function (renderCtx) {
                var _this = this;
                this._initValidators(renderCtx);

                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                formCtx.registerGetValueCallback(formCtx.fieldName, function () {
                    return _this._onGetValue();
                });

                return this._wrapIntoInput(renderCtx, "", 0) + "-" + this._wrapIntoInput(renderCtx, "", 1) + "-" + this._wrapIntoInput(renderCtx, "", 2) + "-" + this._wrapIntoInput(renderCtx, "", 3) + this._wrapErrorArea(renderCtx);
            };

            VisaField.prototype.editFormTemplate = function (renderCtx) {
                var _this = this;
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                var fieldValue = renderCtx.CurrentItem[renderCtx.CurrentFieldSchema.Name];

                this._initValidators(renderCtx);

                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                formCtx.registerGetValueCallback(formCtx.fieldName, function () {
                    return _this._onGetValue();
                });

                if (fieldValue.length == 16) {
                    return this._wrapIntoInput(renderCtx, VisaFieldHelper.ParseValuePart(fieldValue, 0), 0) + "-" + this._wrapIntoInput(renderCtx, VisaFieldHelper.ParseValuePart(fieldValue, 1), 1) + "-" + this._wrapIntoInput(renderCtx, VisaFieldHelper.ParseValuePart(fieldValue, 2), 2) + "-" + this._wrapIntoInput(renderCtx, VisaFieldHelper.ParseValuePart(fieldValue, 3), 3) + this._wrapErrorArea(renderCtx);
                }

                return fieldValue;
            };

            VisaField.prototype.displayFormTemplate = function (renderCtx) {
                if (renderCtx != null && renderCtx.CurrentFieldValue != null) {
                    var fieldValue = renderCtx.CurrentFieldValue.toString();

                    if (fieldValue.length == 16)
                        fieldValue = this._getViewStringValue(fieldValue);

                    return fieldValue;
                }

                return '';
            };

            VisaField.prototype.onError = function (error) {
                if (this._errorContainerId != null) {
                    document.getElementById(this._errorContainerId).innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
                }
            };

            VisaField.prototype.Init = function () {
                var _this = this;
                var fieldName = this._fieldName;

                var visaFieldTemplates = {
                    Templates: {
                        Fields: {}
                    }
                };

                visaFieldTemplates.Templates.Fields[fieldName] = {};

                visaFieldTemplates.Templates.Fields[fieldName]["View"] = function (renderCtx, field, listItem, listSchema) {
                    return _this.viewTemplate(renderCtx, field, listItem, listSchema);
                };
                visaFieldTemplates.Templates.Fields[fieldName]["NewForm"] = function (renderCtx) {
                    return _this.newFormTemplate(renderCtx);
                };
                visaFieldTemplates.Templates.Fields[fieldName]["EditForm"] = function (renderCtx) {
                    return _this.editFormTemplate(renderCtx);
                };
                visaFieldTemplates.Templates.Fields[fieldName]["DisplayForm"] = function (renderCtx) {
                    return _this.displayFormTemplate(renderCtx);
                };

                SPClientTemplates.TemplateManager.RegisterTemplateOverrides(visaFieldTemplates);
            };
            return VisaField;
        })();
        fields.VisaField = VisaField;

        var VisaFieldGridEditControl = (function () {
            function VisaFieldGridEditControl() {
                this._gridContext = null;
                this._gridTextInputElement = null;
                this._cnt = null;
                this._cellContext = null;
                this._tbs = [];
                this._inEdit = false;
                this.SupportedWriteMode = SP.JsGrid.EditActorWriteType.LocalizedOnly;
                this.SupportedReadMode = SP.JsGrid.EditActorReadType.LocalizedOnly;
            }
            VisaFieldGridEditControl.prototype.Init = function (gridContext, gridTextInputElement) {
                var self = this;

                this._onActivateActor = function () {
                    self._gridContext.OnActivateActor();
                };
                this._onKeyDown = function (e) {
                    self.onKeyDown(e);
                };
                this._onKeyUp = function (e) {
                    self.onKeyUp(e);
                };
                this._onMouseDown = function (e) {
                    self.onMouseDown(e);
                };

                this._gridContext = gridContext;
                this._gridTextInputElement = gridTextInputElement;

                this._cnt = document.createElement('div');
                this._cnt.style.cssText = 'visibility:hidden;position:absolute;top:0px;left:0px;background:#ffffff;border:1px #dedede solid;';

                for (var i = 0; i < 4; i++) {
                    var newTb = document.createElement('input');

                    newTb.id = "spdevlab-visafield-quickedit-" + i.toString();
                    newTb.value = i.toString();
                    newTb.style.cssText = 'position:;top:0px;left:0px;';
                    newTb.maxLength = 4;
                    newTb.size = 4;

                    this._cnt.appendChild(newTb);
                    this._tbs[i] = newTb;
                }

                this._gridContext.parentNode.appendChild(this._cnt);
            };

            VisaFieldGridEditControl.prototype.onKeyDown = function (eventInfo) {
                if (eventInfo.keyCode == Sys.UI.Key.tab) {
                    eventInfo.stopPropagation();
                } else {
                    this._gridContext.OnKeyDown(eventInfo);
                }
            };

            VisaFieldGridEditControl.prototype.onKeyUp = function (eventInfo) {
            };

            VisaFieldGridEditControl.prototype.onMouseDown = function (eventInfo) {
                this._tbs[0].focus();
                eventInfo.stopPropagation();
            };

            VisaFieldGridEditControl.prototype._setupHandlers = function (attachActions) {
                var self = this;

                for (var i = 0; i < this._tbs.length; i++) {
                    var tb = this._tbs[i];

                    if (attachActions) {
                        $addHandler(tb, 'focus', self._onActivateActor);
                        $addHandler(tb, 'keydown', self._onKeyDown);
                        $addHandler(tb, 'keyup', self._onKeyUp);
                        $addHandler(tb, 'mousedown', self._onMouseDown);
                    } else {
                        $removeHandler(tb, 'focus', self._onActivateActor);
                        $removeHandler(tb, 'keydown', self._onKeyDown);
                        $removeHandler(tb, 'keyup', self._onKeyUp);
                        $removeHandler(tb, 'mousedown', self._onMouseDown);
                    }
                }
            };

            VisaFieldGridEditControl.prototype.BindToCell = function (cellContext) {
                this._cellContext = cellContext;
            };

            VisaFieldGridEditControl.prototype.OnCellMove = function () {
            };

            VisaFieldGridEditControl.prototype.Focus = function (eventInfo) {
                try  {
                    this._tbs[0].focus();
                } catch (error) {
                    alert('Incorrectly trying to focus the EditBoxEditControl while hidden?');
                }
            };

            // TODO, make the same "parse" method for both quick edit and regular classes
            VisaFieldGridEditControl.prototype.OnBeginEdit = function (eventInfo) {
                this._inEdit = true;

                var currentValue = this._cellContext.originalValue.localized;

                if (currentValue) {
                    VisaFieldHelper.UpdateValues(this._tbs, currentValue);
                }

                this._cellContext.Show(this._cnt);

                this._setupHandlers(true);
                this.Focus(eventInfo);
            };

            VisaFieldGridEditControl.prototype.OnEndEdit = function (eventInfo) {
                this._cellContext.Hide(this._cnt);

                this._inEdit = false;
                this._setupHandlers(false);

                var value = this._tbs[0].value + "" + this._tbs[1].value + "" + this._tbs[2].value + "" + this._tbs[3].value;

                this._cellContext.SetCurrentValue({
                    localized: value
                });
            };

            VisaFieldGridEditControl.prototype.Unbind = function () {
            };
            VisaFieldGridEditControl.prototype.Dispose = function () {
            };
            return VisaFieldGridEditControl;
        })();
        fields.VisaFieldGridEditControl = VisaFieldGridEditControl;

        var VisaFieldValidator = (function () {
            function VisaFieldValidator() {
            }
            VisaFieldValidator.prototype.Validate = function (value) {
                var value = SPClientTemplates.Utility.Trim(value);

                var hasError = !VisaFieldValidator._re16digit.test(value);
                var errorMsg = hasError ? VisaFieldValidator._re16digitErrorMessage : '';

                return new SPClientForms.ClientValidation.ValidationResult(hasError, errorMsg);
            };
            VisaFieldValidator._re16digit = /^\d{16}$/;
            VisaFieldValidator._re16digitErrorMessage = "Please, fill out 4 digits per every text field.";
            return VisaFieldValidator;
        })();
        fields.VisaFieldValidator = VisaFieldValidator;
    })(spdevlab.fields || (spdevlab.fields = {}));
    var fields = spdevlab.fields;

    (function () {
        // general field support
        var field = new spdevlab.fields.VisaField("VisaField");
        field.Init();

        // quick edit support -> yeap, I did it! :)
        SP.SOD.executeOrDelayUntilScriptLoaded(function () {
            SP.GanttControl.WaitForGanttCreation(function (ganttChart) {
                var visaColumn = null;

                var visaFieldQuickEditId = "EDIT_SPDLAB_VISAFIELD";
                var columns = ganttChart.get_Columns();

                for (var i = 0; i < columns.length; i++) {
                    if (columns[i].columnKey == "VisaField") {
                        visaColumn = columns[i];
                        break;
                    }
                }

                visaColumn.fnGetEditControlName = function (record, fieldKey) {
                    return visaFieldQuickEditId;
                };

                SP.JsGrid.PropertyType.Utils.RegisterEditControl(visaFieldQuickEditId, function (gridContext, cellControl) {
                    var editorInstance = new spdevlab.fields.VisaFieldGridEditControl();
                    editorInstance.Init(gridContext, cellControl);

                    return editorInstance;
                }, []);
            });
        }, "spgantt.js");
    })();
})(spdevlab || (spdevlab = {}));
